<?php
namespace Core\Model;

class Base extends \Core\Base {
    public $table;
    /**
     * @var \Core\Db\Mysql
     */
    protected $db;
    protected $error;
    protected function setError($err) {
        $this->error = $err;
    }
    public function getError() {
        $e = $this->error;
        $this->error = '';
        return $e;
    }

    public function getDb() {
        return $this->db;
    }
    
   public function insert($data) {
       return $this->db->insert($this->table,$data);
   }

    public function updateAttr(string $set, $where = '') {
        return $this->db->updateAttr($this->table,$set,$where);
    }

    public function update(array $bind, $where = '') {
        return $this->db->update($this->table,$bind,$where);
    }

    public function delete($where) {
        return $this->db->delete($this->table,$where);
    }

    public function fetch($where = '',$bind=[],$limit = 0,$orderBy='',$fields='*',$offset=0,$ext = '') {
        $sql = 'select '.$fields.' from '.$this->table;
        if(!empty($where)) {
            $sql .= ' where ';
            if(is_string($where)) {
                $sql .= $where;
            }else {
                foreach ($where as $k=>$v) {
                    $k = str_replace('`','',$k);
                    $sql .= '`'.$k.'`'.' = :'.$k.' AND ';
                    $bind[':'.$k] = $v;
                }
                if(!empty($bind)) {
                    $sql = substr($sql,0,-4);
                }
            }
        }
        if($orderBy) {
            $sql .= ' ORDER BY '.$orderBy;
        }
        if($limit == 1) {
            if($offset > 0) {
                $sql .= ' limit '.$offset.',1';
            }
            return $this->db->fetchRow($sql.' '.$ext,$bind);
        }else {
            if($limit > 0) {
                $sql .= ' limit '.$offset.','.$limit;
            }
            return $this->db->fetchAll($sql.' '.$ext,$bind);
        }
    }

    public function count($where,$bind=[],$field = '*') {
        $sql = 'select count('.$field.') as num from '.$this->table;
        if(!empty($where)) {
            $sql .= ' where ';
            if(is_string($where)) {
                $sql .= $where;
            }else {
                foreach ($where as $k=>$v) {
                    $k = str_replace('`','',$k);
                    $sql .= '`'.$k.'`'.' = :'.$k.' AND ';
                    $bind[':'.$k] = $v;
                }
                if(!empty($bind)) {
                    $sql = substr($sql,0,-4);
                }
            }
        }
        $ret = $this->db->fetchRow($sql,$bind);
        return $ret['num'];
    }

}
